package com.huanghwh.demo.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @Author: huanghwh
 * @Date: 2023/04/09 下午2:33
 * @Description: 使用Java SDK手动拉取nacos的配置项
 */
public class JavaSdkConfig {

    public static void main(String[] args) {
        String serverAddr = "localhost:8848";
        String dataId = "user-dev.yml";
        String group = "DEFAULT_GROUP";

        try {
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            // 获取配置
            String config = configService.getConfig(dataId, group, 5000);
            System.out.println(config);
            // 发布配置
            //configService.publishConfig();
            // 删除配置
            //configService.removeConfig();
            // 监听配置
            configService.addListener(dataId, group, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    // nacos发生变化时的回调
                    System.out.println("receiveConfigInfo");
                    System.out.println(configInfo);
                }
            });
            //阻塞主线程 
            System.in.read();
        } catch (NacosException | IOException e) {
            e.printStackTrace();
        }
    }
}
